package XML;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.HashSet;

import fragment.Fragment;

public class XMLProcessGenerator {
	
	private static String path = "src/processGen.xml";
	
public static void writeProcess(HashMap<Fragment,HashSet<Fragment>> dependencies){
		
		HashMap<String,Integer> idMap=new HashMap<String,Integer>() ;
		int i=0;
		
		try{
		    // Create file 
		    FileWriter fstream = new FileWriter(path);
		        BufferedWriter out = new BufferedWriter(fstream);
		       
		    out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		    out.write("<graphml>\n");
		    out.write("<graph edgedefault=\"directed\">\n\n");
		        
		    out.write("<!-- data schema -->\n");
		    out.write("<key id=\"name\" for=\"node\" attr.name=\"name\" attr.type=\"string\"/>\n");
		    out.write("\n");
		    
		    out.write("<key id=\"color\" for=\"node\" attr.name=\"process\" attr.type=\"int\"/>\n");
		    out.write(" <default>-1</default>\n");
		    out.write("\n");
		
		    
		    out.write("<!-- nodes -->\n");
		    for(Fragment e : dependencies.keySet()){
		    	out.write("\t<node id=\""+i+"\">\n");
		    	out.write("\t\t<data key=\"name\">"+e.getId()+"</data>\n");
		    	
		    	
		    	if(e.currentProcess() != -1){
		    		out.write("\t\t<data key=\"process\">"+e.currentProcess()+"</data>\n");
		    	}
		    	out.write("\t</node>\n\n");
		    	
		    	idMap.put(e.getId(),i);
		    	i++;
		    }
		    
		    out.write("<!-- edges -->\n");
		    for(Fragment f : dependencies.keySet()){
		    	for(Fragment d : dependencies.get(f)){
		    		out.write("\t<edge source =\"" + idMap.get(d.getId()) +"\" target=\"" + idMap.get(f.getId())+"\"></edge>\n");
		    	}
		    }
		    
		    
			out.write("\n</graph>\n");
			out.write("</graphml>\n");
		    
		    //Close the output stream
		    out.close();
		    }catch (Exception e){//Catch exception if any
		      System.err.println("Error: " + e.getMessage());
		    }
	}
}
